/*
 * Copyright 2013-2018 Lilinfeng.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wish.nettyprotocol.server;

import java.io.IOException;

import com.wish.nettyprotocol.common.NettyConstant;
import com.wish.nettyprotocol.codec.NettyMessageDecoder;
import com.wish.nettyprotocol.codec.NettyMessageEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;


/**
 * 1、分布式组网环境下，每个Netty节点（Netty进程）之间进行长连接，使用Netty协议进行通信
 * 2、Netty节点并没有服务端和客户端的区别，谁先发起连接则作为客户端，另一方自然成为服务端
 * 3、本次自定义协议栈功能：
 * -- 基于Netty的高性能异步通讯能力
 * -- 提供消息编解码，提供POJO的序列化及反序列化
 * -- 提供基于IP地址的白名单认证机制
 * -- 链路有效性校验机制
 * -- 链路断链重连机制
 *
 * @author tantexian
 * @since 2016/7/19
 */
public class NettyServer {

    public void bind() throws Exception {
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            // backlog其实是一个连接队列, backlog队列总和=未完成三次握手队列 + 已经完成三次握手队列
            .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) // 增加一个日志处理
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); //自定义message解码类
                    ch.pipeline().addLast(new NettyMessageEncoder()); //自定义message编码类
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); // 50秒超时设置
                    ch.pipeline().addLast(new LoginAuthRespHandler()); // 自定义权限认证处理
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());// 自定义心跳处理
                    ch.pipeline().addLast(new RandomReceiveHandler());
                }
            });

        // 绑定端口，同步等待成功
        serverBootstrap.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
        System.out
            .println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    }


    public static void main(String[] args) throws Exception {
        new NettyServer().bind();
    }
}
